package com.immunology.web;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.immunology.domain.Patient;
import com.immunology.service.PatientService;
import com.immunology.web.formatter.DateFormatter;

@Controller
public class PatientController {
    private static final Logger LOG = Logger.getLogger(PatientController.class);
    @Autowired
    private PatientService patientService;

    @RequestMapping(value = "patientRegistration", method = RequestMethod.GET)
    public ModelAndView addPatient(ModelMap model) {
	ModelAndView result = null;
//	Patient patient = patientService.findById(46L);
	// String date = new String("Hello");
	// Map<String, Object> parameterMap = new HashMap<String, Object>();
	// parameterMap.put("patient", patient);
	// parameterMap.put("date", date);
	Patient patient = new Patient();
	result = new ModelAndView("patientRegistration", "patient", patient);
	return result;
    }

    @RequestMapping(value = "patientRegistration", method = RequestMethod.POST)
    public ModelAndView onSubmit(HttpServletRequest request,
	    @ModelAttribute("patient") @Valid Patient patient,
	    BindingResult bindingResult) throws Exception {
	ModelAndView result = null;
	if (bindingResult.hasErrors()) {
	    result = new ModelAndView("patientRegistration", "patient", patient);
	} else {
	    String date = request.getParameter("date");
	    Date birthday = DateFormatter.createDate(date);
	    patient.setBirthday(birthday);
	    patientService.saveOrUpdate(patient);
	    result = new ModelAndView("redirect:patientAll");
	}
	return result;
    }

    @RequestMapping(value = "patientAll", method = RequestMethod.GET)
    public ModelAndView getAll(ModelMap model) {
	ModelAndView result = null;
	List<Patient> patients = new ArrayList<Patient>();
	patients = patientService.getAll();
	result = new ModelAndView("patientAll", "patients", patients);
	return result;
    }

}
